package com.fzz.learnitservice.controller;


import com.commonfzz.pojo.po.R;
import com.fzz.learnitservice.context.UserContext;
import com.fzz.learnitservice.pojo.po.ChatMemory;
import com.fzz.learnitservice.service.IAIService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class AIController {

    private final IAIService aiService;

    @GetMapping("/chat")
    public R<String> chat(@RequestParam String question) {
        return R.ok(aiService.chat(question));
    }

    /**
     * AI对话，流式响应
     * @param question
     * @return
     */
    @GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chatStream(@RequestParam String question) {
        SseEmitter emitter = new SseEmitter(300000L); // 5分钟超时
        
        // 在异步执行前获取当前线程的userId，避免异步线程中ThreadLocal为null
        Long userId = UserContext.getUserId();
        
        // 调用Service层处理流式响应
        aiService.chatStreamWithSse(question, emitter, userId);
        
        return emitter;
    }

    /**
     * 获取用户跟AI对话记录
     * @return
     */
    @GetMapping("/chatRecord")
    public R<List<ChatMemory>> chatRecord() {
        return R.ok(aiService.chatRecord());
    }

    /**
     * 用户编辑某问题
     * @param question
     * @param id
     * @return
     */
    @GetMapping("/edit")
    public SseEmitter edit(@RequestParam String question, @RequestParam Long id) {
        SseEmitter emitter = new SseEmitter(300000L); // 5分钟超时

        // 在异步执行前获取当前线程的userId，避免异步线程中ThreadLocal为null
        Long userId = UserContext.getUserId();

        // 调用Service层处理流式响应
        aiService.edit(question, emitter, userId, id);

        return emitter;
    }

    /**
     * 用户删除某问题
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public R delete(@RequestParam Long id) {
        aiService.delete(id);
        return R.ok();
    }

    /**
     * 用户清空对话
     * @return
     */
    @DeleteMapping("/clear")
    public R clear() {
        aiService.clearChatHistory();
        return R.ok();
    }

}
